package controller

import (
	"encoding/json"
	"io/ioutil"
	"kingbloc.dts/services"
	"kingbloc.dts/tools"
	"kingbloc.util/util"
	"net/http"
	"strconv"
	"sync"
)


func NewOrder(rep http.ResponseWriter, req *http.Request) {

	user := validateUserInfo(req)
	var result = map[string]string{}

	if user == nil {
		rep.WriteHeader(403)
		return
	}

	myAccount := service.FindAccountBySSOId(user.Id)

	if myAccount == nil || myAccount.Id == 0 {
		rep.WriteHeader(403)
		return
	}
	// 更具账户类型报单
	if myAccount.Types == 0 {
		result["status"] = "1"
		result["msg"] = "报单失败，没有权限！"
		util.WriteJSON(rep, result)
		return
	}

	//
	price, introducerMob, mob, result1, sta := valiParams(req)
	if !sta {
		rep.WriteHeader(403)
		util.WriteJSON(rep, result1)
		return
	}

	//
	//
	//
	var onOrderId int64
	introducerAccount := service.FindAccountByMob(introducerMob)
	introducerOrders := service.FindOrdersByAccountId(introducerAccount.Id)
	// 第一个单必须是别人报的
	if len(introducerOrders) < tool.GlobalMultiply_2 {
		onOrderId = introducerOrders[0].ParentId
	} else {
		onOrderId = introducerOrders[0].Id
	}

	priceVal, _ := strconv.ParseFloat(price, 64)

	lockNewOrder := new(sync.Mutex)
	if myAccount.Types == 2 {
		result = service.PlaceAnOrder(mob, introducerMob, onOrderId, priceVal, false, lockNewOrder)
	} else {
		result = service.PlaceAnOrder(mob, introducerMob, onOrderId, priceVal, true, lockNewOrder)

	}

	result["status"] = "10"
	result["msg"] = "报单成功！"

	util.WriteJSON(rep, result)
	//
	new(service.Award).CalcAwardLayer()

	msg := &service.Msg{Topic: "test", Method: "newOrderOk", Data: "有人报单啦！"}
	service.Publish(msg)

}
func valiParams(req *http.Request) (price string, introducerMob string, mob string, result map[string]string, sta bool) {
	body, _ := ioutil.ReadAll(req.Body)
	params := make(map[string]string, 0)
	json.Unmarshal(body, &params)

	mob = params["mobile"]
	price = params["price"]
	introducerMob = params["introducerMob"]
	if !tool.ExtisPrice(price) {

		sta = false

	}
	if introducerMob == "" || price == "" || mob == "" {
		result["status"] = "2"
		result["msg"] = "报单失败，信息不正确！"
		sta = false
	}
	if !util.RegexpMobile.MatchString(mob) || !util.RegexpMobile.MatchString(introducerMob) {
		result["status"] = "3"
		result["msg"] = "报单失败，手机号格式不正确！"
		sta = false
	}
	return
}
